import express from 'express';
import type { Express, Request, Response } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import { errorHandler } from './middleware/errorHandler';
import prisma from './lib/prisma';
import { hashPassword } from './utils/auth';

function createApp(): Express {
  const app: Express = express();

  // 基础中间件
  app.use(helmet());
  app.use(cors());
  app.use(compression());
  app.use(express.json());

  // 健康检查
  app.get('/health', (_req: Request, res: Response): void => {
    res.json({ status: 'ok' });
  });

  // 简单用户路由用于测试
  app.post('/api/users', async (req: Request, res: Response): Promise<void> => {
    const { email, password, name, role } = req.body;
    try {
      // 检查邮箱是否存在
      const existingUser = await prisma.user.findUnique({
        where: { email }
      });

      if (existingUser) {
        res.status(400).json({ error: 'Email already exists' });
        return;
      }

      // 创建新用户
      const hashedPassword = await hashPassword(password);
      const user = await prisma.user.create({
        data: {
          email,
          password: hashedPassword,
          name,
          role
        }
      });

      // 返回用户信息（不包含密码）
      const { password: _, ...userWithoutPassword } = user;
      res.status(201).json(userWithoutPassword);
    } catch (error) {
      console.error('User creation failed:', error);
      res.status(400).json({ error: 'User creation failed' });
    }
  });

  // 错误处理
  app.use(errorHandler);

  return app;
}

export default createApp;
